﻿$(function () {
    var myDialog = null;
    var Page_Size = 5;
    $("#btnFilterUser").live("click", GetDataClick);
    $("#Sdate").live("focus", txtSdateConfig);//开始日期控件配置
    $("#Edate").live("focus", txtEdateConfig);//截止日期控件配置
    $("#btnFilterQA").live("click", btnSearchQAClick);//QA查询
    $("#tbQAs tbody tr").live("click", tbQAsClick);//QA数据行点击
    $("#btnCloseQA").live("click", function () { myDialog.close() });//关闭对话框
    $("#btnAnswerQA").live("click", btnAnswerQAClick);//QA回复
    $("#btnFilterUnAnswer").live("click", btnGetNoAnswerQAClick);//查询未回复的Qa
    $("#btnFilterJoin").live("click", btnSearchJoinClick);//加盟申请列表
    $("#FSdate").live("focus", txtSdateConfig);//开始日期控件配置
    $("#FEdate").live("focus", txtEdateConfig);//截止日期控件配置

    $("#SdateOfJoin").live("focus", txtSdateConfig);//开始日期控件配置
    $("#EdateOfJoin").live("focus", txtEdateConfig);//截止日期控件配置

    $("#btnAddUser").live("click", btnAddUserClick);//用户新增
    $("#btnEditUser").live("click", btnEditUserClick);//用户编辑
    $("#btnEnableUser").live("click", btnEnableUserClick);//用户启用
    $("#btnDisenableUser").live("click", btnDisenableUserClick);//用户关闭

    $("#btnCloseEdituser").live("click", function () { editUserDialog.close() });//关闭对话框
    $("#btnCloseAdduser").live("click", function () { addUserDialog.close() });//关闭对话框//
    $("#btnCloseJuser").live("click", function () { JoinUserDialog.close() });//关闭对话框

    $("#btnInsertUser").live("click", btnInsertUserClick);//用户新增
    $("#btnModifyUser").live("click", btnModifyUserClick);//用户编辑
    $("#tbJoinLogs tr").live("click", tbJoinLogsTrClick);//加盟申请行记录点击
    $("#btnSuccessApply").click(btnSuccessApplyClick);//加盟成功按钮
    $("#btnAddUserForJoin").live("click",btnAddUserForJoinClick);//加盟成功 同时创建用户信息
    $("#btnBadApply").live("click", btnBadApplyClick);//恶意提交
    $("#btnHandleringApply").live("click", btnHandleringApplyClick);//审核中
    $("#btnModifyUserForJoin").live("click", btnModifyUserForJoinClick);//加盟用户备注修改

    function btnBadApplyClick()
    {
        btnHandlerApply(2);
    }

    function btnHandleringApplyClick() {
        btnHandlerApply(0);
    }

    function btnHandlerApply(handlerStatus)
    {
        var $selectedTr = $("#tbJoinLogs tr.danger");
        if ($selectedTr.length == 0) {
            alert("请点击需要处理的申请记录")
        }
        else {
            var $tr = $selectedTr.first();
            var joinFormId = $tr.attr("data-joinApplyFormId");
            $.ajax({
                url: "../WebAdmin/BadApply",
                data: { joinApplyId: joinFormId, handlerStatus: handlerStatus },
                dataType: "json",
                beforeSend: function () {

                },
                type: "post",
                success: function (result) {
                    if (result.Result.IsSuccess) {
                        alert("操作成功", function () {
                            $("#btnFilterJoin").click();
                        });
                    }
                    else {
                        alert(result.Result.ErrMessage);
                    }
                },
                async: true,
                complete: function () {

                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(errorThrown);
                }
            });
        }
    }

    function btnAddUserForJoinClick()
    {
        var userName = $("#jtxtUserName").val();
        var rolerId = $("#divUserAddForJoin #FilterRolers option:selected").val();
        var note = $("#jtxtNote").val();
        var joinApplyId = $("#spanJoinApplyFormId").text();
        if (userName == "") {
            alert("请输入用户名");
            return;
        }

        if (rolerId == "-1") {
            alert("请选择角色");
            return;
        }

        var data = { userName: userName, rolerId: rolerId, note: note, joinApplyId: joinApplyId };
        $.ajax({
            url: "../WebAdmin/SuccessJoin",
            data: data,
            dataType: "json",
            beforeSend: function () {

            },
            type: "post",
            success: function (result) {
                if (result.Result.IsSuccess) {
                    alert("创建成功", function () {
                        $("#btnCloseJuser").click();
                        $("#btnFilterUser").click();
                        $("#btnFilterJoin").click();
                    });
                }
                else {
                    alert(result.Result.ErrMessage);
                }
            },
            async: true,
            complete: function () {

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    }

    //成功加盟处理
    function btnSuccessApplyClick() {
        var $selectedTr = $("#tbJoinLogs tr.danger");
        if ($selectedTr.length==0) {
            alert("请点击需要处理的申请记录")
        }
        else {
            var $tr = $selectedTr.first();
            var joinFormId = $tr.attr("data-joinApplyFormId");


            $.getJSON("WebAdmin/GetJoinFormById", { joinFormId: joinFormId, now: new Date() }, function (result) {
                var source = $("#UserAddForJoin_template").html();
                var template = Handlebars.compile(source);
                var user = result.User;
                if (user) {
                    result.UserName = user.UserName;
                    result.NoteUser = user.Note;
                    result.UserId = user.UserId;
                }
                var html = template(result);
                JoinUserDialog = art.dialog({
                    content: html,
                    title: '审核通过创建账户',
                    id: 'successJoinDialog',
                }).lock();

                if (user) {
                    $("#jtxtUserName").attr("disabled", "disabled");
                   // $("#jtxtNote").attr("disabled", "disabled");
                    $("#btnAddUserForJoin").hide();
                    $("#btnModifyUserForJoin").show();
                }
                var joinType = result.JoinApplyTypeStr;//根据加盟类型限制创建帐号角色
               // $("#divUserAddForJoin #FilterRolers option[html=" + joinType + "]").attr("selected", "selected");
                var $options = $("#divUserAddForJoin #FilterRolers option");
                $.each($options, function (k, v) {
                    var $current = $(v);
                    if ($current.html() == joinType)
                    {
                        $current.attr("selected", "selected");
                    }
                });

               $("#divUserAddForJoin #FilterRolers").attr("disabled","disabled");
            });

        }
    }

    function tbJoinLogsTrClick() {
        $("#tbJoinLogs tr").removeClass("danger");
        $(this).addClass("danger");
    }

    $("#spanProviceCity").chinaprovinces({
        valueType: 'name', change: function (province, city, area) {
            $("#AddressProviceCn").val(province);
            $("#AddressCityCn").val(city);
            $("#AddressZoneCn").val(area);
        }
    });

    $("#spanProviceCityJapan").chinaprovinces({
        valueType: 'name', change: function (province, city, area) {
            $("#AddressProviceJapan").val(province);
            $("#AddressCityJapan").val(city);
            $("#AddressZoneJapan").val(area);
        }
    });


    $("#JoinApplyTypeSel").change(function () {
        var value = $(this).val();

        // alert(value);
        if (value == 0) {
            $("#InnerModel").hide();
            $("#JapanModel").hide();
        }

        if (value == 1) {
            $("#InnerModel").show();
            $("#JapanModel").hide();
        }

        if (value == 2) {
            $("#InnerModel").hide();
            $("#JapanModel").show();
        }
    });
    //
    //
    $("#btnFilterUser").click();
    $("#checkUserAll").click(function () {
        if ($(this).attr("checked") == "checked") {
            $(".userCheck").attr("checked", "checked");
        } else {
            $(".userCheck").removeAttr("checked");
        }
    });


    function btnInsertUserClick() {
        var userName = $("#txtUserName").val();
        var rolerId = $("#divUserAdd #FilterRolers option:selected").val();
        var note = $("#txtNote").val();

        if (userName == "") {
            alert("请输入用户名");
            return;
        }

        if (rolerId == "-1") {
            alert("请选择角色");
            return;
        }

        var data = { userName: userName, rolerId: rolerId, note: note };
        $.ajax({
            url: "../WebAdmin/AddUser",
            data: data,
            dataType: "json",
            beforeSend: function () {

            },
            type: "post",
            success: function (result) {
                if (result.Result.IsSuccess) {
                    alert("创建成功", function () {
                        $("#btnCloseAdduser").click();
                        $("#btnFilterUser").click();
                    });
                }
                else {
                    alert(result.Result.ErrMessage);
                }
            },
            async: true,
            complete: function () {

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });

    }

    function btnAddUserClick() {
        var source = $("#UserAdd_template").html();
        var template = Handlebars.compile(source);
        var html = template();
        addUserDialog = art.dialog({
            content: html,
            title: '创建新用户',
            id: 'addUserDialog',
        }).lock();
    }

    function btnEditUserClick() {
        var checkedBoxs = $(".userCheck:checked");
        if (checkedBoxs.length == 0) {
            alert("未勾选任何数据");
            return;
        }
        if (checkedBoxs.length > 1) {
            alert("每次只能编辑一个用户");
            return;
        }
        userId = $(checkedBoxs[0]).attr("data-userid");

        $.getJSON("WebAdmin/GetUserInfoById", { userId: userId, now: new Date() }, function (result) {
            var source = $("#UserEdit_template").html();
            var template = Handlebars.compile(source);
            var html = template(result);
            editUserDialog = art.dialog({
                content: html,
                title: '用户编辑',
                id: 'editDialog',
            }).lock();
            $("#divUserEdit #FilterRolers option[value=" + result.RolerId + "]").attr("selected", "selected");

        });

    }


    function btnModifyUserClick() {
        var userName = $("#etxtUserName").val();
        var rolerId = $("#divUserEdit #FilterRolers option:selected").val();
        var note = $("#etxtNote").val();
        var userId = $(this).attr("data-userId");

        if (userName == "") {
            alert("请输入用户名");
            return;
        }

        if (rolerId == "-1") {
            alert("请选择角色");
            return;
        }

        var data = { newUserName: userName, userId: userId, newRolerId: rolerId, note: note };
        $.ajax({
            url: "../WebAdmin/ModifyUser",
            data: data,
            dataType: "json",
            beforeSend: function () {

            },
            type: "post",
            success: function (result) {
                if (result.Result.IsSuccess) {
                    alert("编辑成功", function () {
                        $("#btnCloseEdituser").click();
                        $("#btnFilterUser").click();
                    });
                }
                else {
                    alert(result.Result.ErrMessage);
                }
            },
            async: true,
            complete: function () {

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    }

    function btnModifyUserForJoinClick() {
        var userName = $("#jtxtUserName").val();
        var rolerId = $("#divUserAddForJoin #FilterRolers option:selected").val();
        var note = $("#jtxtNote").val();
        var userId = $(this).attr("data-userId");

        if (userName == "") {
            alert("请输入用户名");
            return;
        }

        if (rolerId == "-1") {
            alert("请选择角色");
            return;
        }

        var data = { newUserName: userName, userId: userId, newRolerId: rolerId, note: note };
        $.ajax({
            url: "../WebAdmin/ModifyUser",
            data: data,
            dataType: "json",
            beforeSend: function () {

            },
            type: "post",
            success: function (result) {
                if (result.Result.IsSuccess) {
                    alert("保存成功", function () {

                    });
                }
                else {
                    alert(result.Result.ErrMessage);
                }
            },
            async: true,
            complete: function () {

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    }
    //开启
    function btnEnableUserClick() {
        UserStatus(false);
    }

    //关闭
    function btnDisenableUserClick() {
        UserStatus(true);
    }

    function UserStatus(isDelete) {
        var checkedBoxs = $(".userCheck:checked");

        if (checkedBoxs.length == 0) {
            alert("未勾选任何数据");
            return;
        }
        var userIdStr = "";
        $.each(checkedBoxs, function (key, value) {
            userIdStr += $(value).attr("data-userid") + "$";
        });
        var data = { userIdStr: userIdStr, isDelete: isDelete };

        // alert(data.userIdStr + "---" + data.isDelete);
        $.ajax({
            url: "../WebAdmin/UserStatus",
            data: data,
            dataType: "json",
            beforeSend: function () {

            },
            type: "post",
            success: function (result) {
                if (result.Result.IsSuccess) {
                    alert("操作成功", function () {
                        $("#btnFilterUser").click();
                    });
                }
                else {
                    alert(result.Result.ErrMessage);
                }
            },
            async: true,
            complete: function () {

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    };

    function btnAnswerQAClick() {
        var qaId = $(this).attr("data-qaId");
        var answerContent = $.trim($("#AnswerContent").val());
        if (qaId == undefined) {
            alert("qa编号丢失");
            return;
        }
        //if (!answerContent) {
        //    alert("回答内容不得为空");
        //    return;
        //}
        $.getJSON("WebAdmin/AnswerQA", { qaId: qaId, answerContent: answerContent }, function (result) {
            if (result.Result.IsSuccess) {
                myDialog.close();
                art.dialog.notice({
                    width: 120,
                    content: '回复成功',
                    icon: 'succeed',
                    time: 3
                });
                $("#btnFilterQA").click();
            }
            else {
                art.dialog({
                    content: result.Result.ErrMessage
                });
            }
        });
    }
    function tbQAsClick() {
        var qaId = $(this).attr("data-qaId");
        $.getJSON("WebAdmin/GetQAById", { qaId: qaId, now: new Date() }, function (result) {
            var source = $("#QAAnswer-template").html();
            var template = Handlebars.compile(source);
            var html = template(result);
            myDialog = art.dialog({
                content: html,
                title: '问题答复对话框',
                id: 'qaDialog',
            }).lock();
        });
    }

    function UserFilter(rolerId, isActive, page, flowStepId, changeStartTime, changeEndTime) {
        if (isActive != "-1") {
            this.IsActive = isActive;
        }
        if (rolerId == "-1") {
            rolerId = "";
        }

        if (flowStepId != "-1") {
            this.FlowStepId = flowStepId;
        }

        if (changeStartTime != "") {
            this.ChangeStartTime = changeStartTime;
        }

        if (changeEndTime != "") {
            this.ChangeEndTime = changeEndTime;
        }

        this.RolerId = rolerId;
        this.PageSize = Page_Size;
        this.Page = page;
    }

    function GetDataClick() {
        var rolerId = $("#FilterRolers option:selected").val();
        var isActive = $("#IsActive option:selected").val();
        var flowStepId = $("#flowStepList option:selected").val();
        var changeStartTime = $("#FSdate").val();
        var changeEndTime = $("#FEdate").val();
        var filter = new UserFilter(rolerId, isActive, 1, flowStepId, changeStartTime, changeEndTime);
        GetDataPage(filter);
    }

    function GetDataPage(f) {
        //分页控件   
        var count = GetDataCount(f);
        $("#pp").pagination(count, {
            link_to: "javascript:void(0)",
            num_edge_entries: 2, //边缘页数
            num_display_entries: 7, //主体页数
            callback: onSelectPageFun,
            items_per_page: Page_Size, //每页显示项
            prev_text: "&laquo;",
            next_text: "&raquo;"
        });

        //响应事件
        function onSelectPageFun(page) {
            var $img = getLoadPic();
            var $tbody = $("#tbUsers tbody");
            f.Page = page + 1;
            var url = "WebAdmin/GetUsers";
            $.ajax({
                url: url,
                data: f,
                dataType: "json",
                beforeSend: function () {
                    $tbody.empty();
                    $tbody.append($img);
                },
                type: "post",
                success: function (result) {
                    renderFun(result);//响应事件
                },
                async: true,
                complete: function () {
                    $img.remove();
                }
            });
        }
        //END
    };

    //数据渲染
    function renderFun(result) {
        $("#checkUserAll").removeAttr("checked");//数据刷新后移除全选钩
        var $tbody = $("#tbUsers tbody");
        $tbody.empty();
        $.each(result, function (key, value) {
            $tr = $("<tr>");
            $td0 = $("<td>", { html: "<input type=checkbox class='userCheck' data-userId=" + value.UserId + " />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" });
            $td1 = $("<td>", { html: value.UserId });
            $td2 = $("<td>", { html: value.UserName });
            $td3 = $("<td>", { html: value.RolerName });
            $td4 = $("<td>", { html: value.IsDelete == "0" ? "启用" : "关闭" });
            $td5 = $("<td>", { html: value.Note });
            $tr.append($td0).append($td1).append($td2).append($td3).append($td4).append($td5);

            $tr.appendTo($tbody);
        });
    }

    function GetDataCount(f) {
        var count = 0;
        $.ajax({
            url: "WebAdmin/GetUsersCount",
            data: f,
            success: function (res) {
                count = res;
            },
            async: false,
            type: "post"
        });
        return count;
    };

    function txtSdateConfig() {
        var endValue = new Date();
        WdatePicker({
            minDate: '1900-01-01', maxDate: endValue,
            onpicked: function () {

            }
        });
    }

    function txtEdateConfig() {
        var endValue = new Date();
        WdatePicker({
            minDate: '1900-01-01',
            onpicked: function () {

            }
        })
    }

    //QA
    GetQAPage({ page: 1, pageSize: Page_Size });

    //获取未回答的QA
    function btnGetNoAnswerQAClick() {
        GetQAPage({ Page: 1, PageSize: Page_Size, NoAnswerFlag: true });
    }

    function btnSearchQAClick() {
        var Sdate = $("#Sdate").val();
        var Edate = $("#Edate").val();
        GetQAPage({ Page: 1, PageSize: Page_Size, Sdate: Sdate, Edate: Edate });
    }
    function GetQAPage(f) {
        //分页控件   
        var count = GetQADataCount(f);
        $("#pp2").pagination(count, {
            link_to: "javascript:void(0)",
            num_edge_entries: 2, //边缘页数
            num_display_entries: 7, //主体页数
            callback: onSelectPageFun,
            items_per_page: Page_Size, //每页显示项
            prev_text: "&laquo;",
            next_text: "&raquo;"
        });

        //响应事件
        function onSelectPageFun(page) {
            var $img = getLoadPic();
            var $tbody = $("#tbQAs tbody");
            f.page = page + 1;
            var url = "../WebAdmin/GetQAList";
            $.ajax({
                url: url,
                data: f,
                dataType: "json",
                beforeSend: function () {
                    $tbody.empty();
                    $tbody.append($img);
                },
                type: "post",
                success: function (result) {
                    renderQAFun(result);//响应事件
                },
                async: true,
                complete: function () {
                    $img.remove();
                }
            });
        }
        //END
    };

    //数据渲染
    function renderQAFun(result) {
        var $container = $("#tbQAs tbody");
        $container.empty();

        $.each(result, function (key, value) {
            value.QuestionContent = value.QuestionContent.substring(0, 50) + "...";
        });
        //
        var list = result;
        var source = $("#QA-template").html();
        var template = Handlebars.compile(source);
        var html = template({ qas: list });
        $container.append(html);
    };
    function GetQADataCount(f) {
        var count = 0;
        $.ajax({
            url: "../WebAdmin/GetQACount",
            data: f,
            success: function (res) {
                count = res;
            },
            async: false
        });
        return count;
    }
    //QA END



    //加盟处理
    GetJoinLogPage({ page: 1, pageSize: Page_Size });


    function btnSearchJoinClick() {
        var Sdate = $("#SdateOfJoin").val();
        var Edate = $("#EdateOfJoin").val();
        var companyName = $("#CompanyName").val();
        var selectHandlerState = $("#SelectHandlerState").val();

        var joinApplyTypeSel = $("#JoinApplyTypeSel").val();
        var country = "";//国家

        var data = { Page: 1, PageSize: Page_Size };

        if (companyName != "") {
            data.CompanyName = companyName;
        }

        if (Sdate != "") {
            data.Sdate = Sdate;
        }

        if (Edate != "") {
            data.Edate = Edate;
        }

        if (selectHandlerState != "") {
            data.HandlerStatus = selectHandlerState;
        }

        if (joinApplyTypeSel != "0") {
            data.JoinApplyType = joinApplyTypeSel;
            switch (joinApplyTypeSel) {
                case "1":
                    country = "Cn"; //根据国家分类 取对应控件的值
                    break;
                case "2":
                    country = "Japan";
                    break;
            }
        }

        if (country != "") {
            var companyType = $("#CompanyType" + country).val();
            var addressProvice = $("#AddressProvice" + country).val();
            var addressCity = $("#AddressCity" + country).val();
            var addressZone = $("#AddressZone" + country).val();
            var addressSuffix = $("#AddressSuffix" + country).val();

            // alert(companyType);
            if (companyType != "") {
                data.CompanyType = companyType;
            }
            if (addressProvice != "") {
                data.AddressProvice = addressProvice;
            }
            if (addressCity != "") {
                data.AddressCity = addressCity;
            }
            if (addressZone != "") {
                data.AddressZone = addressZone;
            }
            if (addressSuffix != "") {
                data.AddressSuffix = addressSuffix;
            }
        }

        GetJoinLogPage(data);
    }
    function GetJoinLogPage(f) {
        //分页控件   
        var count = GetJoinDataCount(f);
        $("#pp3").pagination(count, {
            link_to: "javascript:void(0)",
            num_edge_entries: 2, //边缘页数
            num_display_entries: 7, //主体页数
            callback: onSelectPageFun,
            items_per_page: Page_Size, //每页显示项
            prev_text: "&laquo;",
            next_text: "&raquo;"
        });

        //响应事件
        function onSelectPageFun(page) {
            var $img = getLoadPic();
            var $tbody = $("#tbJoinLogs tbody");
            f.page = page + 1;
            var url = "../WebAdmin/GetJoinLogs";
            $.ajax({
                url: url,
                data: f,
                dataType: "json",
                beforeSend: function () {
                    $tbody.empty();
                    $tbody.append($img);
                },
                type: "post",
                success: function (result) {
                    renderJoinFun(result);//响应事件
                },
                async: true,
                complete: function () {
                    $img.remove();
                }
            });
        }
        //END
    };

    //数据渲染
    function renderJoinFun(result) {
        var $container = $("#tbJoinLogs tbody");
        $container.empty();
        var list = result;
        $.each(list, function (k, v) {
            var fileLink = "";
            var JinyingzigeFile = v.JinyingzigeFile;
            var YinyezhizhaoFile = v.YinyezhizhaoFile;
            var MujiyaoxiangFile = v.MujiyaoxiangFile;
            var pathSeverPath = $("#hiddenFilePath").val().substring(2);
            if (JinyingzigeFile) {
                var fileUrl = pathSeverPath + "/" + JinyingzigeFile.FileName;
                var fileType = JinyingzigeFile.FileType.FileTypeName;
                fileLink += "<a class=fileLink target=_blank href=" + fileUrl + ">" + fileType + "</a>|<br/>"
            }

            if (YinyezhizhaoFile) {
                var fileUrl = pathSeverPath + "/" + YinyezhizhaoFile.FileName;
                var fileType = YinyezhizhaoFile.FileType.FileTypeName;
                fileLink += "<a class=fileLink target=_blank href=" + fileUrl + ">" + fileType + "</a><br/>"
            }

            if (MujiyaoxiangFile) {
                var fileUrl = pathSeverPath + "/" + MujiyaoxiangFile.FileName;
                var fileType = MujiyaoxiangFile.FileType.FileTypeName;
                fileLink += "<a class=fileLink target=_blank href=" + fileUrl + ">" + fileType + "</a><br/>"
            }

            v.FileLink = fileLink;
        });
        var source = $("#Join-template").html();
        var template = Handlebars.compile(source);
        var html = template({ joins: list });
        $container.append(html);
    };
    function GetJoinDataCount(f) {
        var count = 0;
        $.ajax({
            url: "../WebAdmin/GetJoinsCount",
            data: f,
            success: function (res) {
                count = res;
            },
            async: false
        });
        //alert(count);
        return count;
    }
    //加盟 处理END

});